import {
  BasicLayoutProps,
  PageLoading,
  // ProBreadcrumb,
} from '@ant-design/pro-layout';
import { history } from 'umi';
import '@/api/config';

import './app.less';

const wait = (time: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

interface InitialState {
  userId: string | null;
  role: string | null;
  permissions: string[];
}

export async function getInitialState(): Promise<InitialState> {
  if (!window.localStorage.getItem('token')) {
    return { userId: '', role: '', permissions: [] };
  }

  await wait(1000);
  return {
    userId: 'admin',
    role: 'admin',
    permissions: [],
  };
}

interface LayoutConfig {
  logout: () => void;
}

export const layout = ({
  initialState,
}: {
  initialState: {
    userId: string;
    role: string;
    permissions: string[];
    token: string;
  };
}): BasicLayoutProps & LayoutConfig => {
  return {
    onPageChange: () => {
      if (
        history.location.pathname === '/login' &&
        window.localStorage.getItem('token')
      ) {
        history.push('/');
      }
      if (!initialState.userId) {
        history.push('/login');
      }
    },
    logout: () => {
      localStorage.clear();
      window.location.reload();
    },
  };
};
